#include <boost/bind.hpp>
#include <boost/asio.hpp>


#include "TCPSession.h"
#include "Common.h"
namespace RisingStar
{

	
	//后面那个参数mIOServicePtr(pIOService) 是用来保持住共享指针计数的，否则线程将会被销毁
	CTCPSession::CTCPSession(IOServicePtr& pIOService):mSocket(*pIOService),mIOServicePtr(pIOService)
	{
		
		
	}
	
	CTCPSession::~CTCPSession()
	{
		
		
	}
	bool CTCPSession::Start()
	{
		mSocket.async_read_some(asio::buffer(mData, MAX_PACKET_LEN),
								boost::bind(&CTCPSession::HandleRead,		//使用handle_read读取数据
								this,
								asio::placeholders::error,
								asio::placeholders::bytes_transferred));
		
		return true;
	}
	void CTCPSession::HandleRead(const boost::system::error_code& error, size_t bytesTransferred)
    {
        if (!error)
        {
			//mData = "服务器回复:" + mData;
			//将数据发还回去
			cout<<"服务器回复"<<endl;
            asio::async_write(	mSocket,
								asio::buffer(mData, bytesTransferred),
								boost::bind(&CTCPSession::HandleWrite, this, asio::placeholders::error)
								);


        }
        else
        {
			
            delete this;	//自我销毁
			_ERROR("自我销毁");
        }
    }
	
	void CTCPSession::HandleWrite(const boost::system::error_code& error)
    {
        if (!error)
        {
            Start();
        }
        else
        {
            delete this;
			//_ERROR("写自我销毁");

        }
    }
	
	ip::tcp::socket& CTCPSession::GetSocket()
    {
        return mSocket;
    }
}